package com.management.demo.utils;

import cn.hutool.jwt.JWT;

import java.security.SecureRandom;
import java.util.Base64;
import java.util.Date;

public class JwtUtils {

    private static final String SECRET_KEY = "mFgOZHni2pREU2q6qYpZjkoUFxPy2HabRtXVSvwD1PY=";

    private static final String TOKEN_KEY = "id";

    private static final long EXPIRATION_TIME = 7200000; // 2 小时

    public static String generateToken(Integer id) {
        return JWT.create().setPayload(TOKEN_KEY, id)
                .setIssuedAt(new Date(System.currentTimeMillis()))
                .setExpiresAt(new Date(System.currentTimeMillis() + EXPIRATION_TIME))
                .setKey(SECRET_KEY.getBytes()).sign();
    }

    public static String extractUserId(String token) {
        return JWT.of(token).getPayload(TOKEN_KEY).toString();
    }

    public static Boolean validateToken(String token, String username) {
        String tokenUsername = extractUserId(token);
        boolean validate = JWT.of(token).setKey(SECRET_KEY.getBytes()).validate(0);
        return (tokenUsername.equals(username) && validate);
    }

    // 生成一个 32 字节的随机字节数组，然后使用 Base64 编码将其转换为字符串作为 SECRET_KEY
    public static void main(String[] args) {
        byte[] keyBytes = new byte[32];
        SecureRandom random = new SecureRandom();
        random.nextBytes(keyBytes);
        String secretKey = Base64.getEncoder().encodeToString(keyBytes);
        System.out.println(secretKey);
    }
}
